import {
  login,
  getInfo,
  loginByCode,
  register,
  loginByPass,
  getProvience,
  getCity
} from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    userInfo: sessionStorage.userInfo || {},
    provienceList: [],
    cityList: []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_USERINFO: (state, userInfo = {}) => {
    state.userInfo = userInfo
    if (userInfo) {
      sessionStorage.userInfo = JSON.stringify(userInfo)
    }
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_PROVIENCE: (state, list = []) => {
    state.provienceList = list
  },
  SET_CITY: (state, list = []) => {
    state.cityList = list
  }
}

const actions = {
  // user login
  loginByCode({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      loginByCode(userInfo)
        .then((response) => {
          if (response.success) {
            commit('SET_USERINFO', response.result.userInfo)
            commit('SET_TOKEN', response.result.token)
            setToken(response.result.token)
          }

          resolve(response)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
  // user login
  loginByPass({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      loginByPass(userInfo)
        .then((response) => {
          if (response.success) {
            commit('SET_USERINFO', response.result.userInfo)
            commit('SET_TOKEN', response.result.token)
            setToken(response.result.token)
          }
          resolve(response)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password })
        .then((response) => {
          if (response.success) {
            const { data } = response
            commit('SET_TOKEN', data.token)
            setToken(data.token)
          }

          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
  register({ commit }, value) {
    return new Promise((resolve, reject) => {
      register(value)
        .then((response) => {
          if (response.success) {
            const { data } = response
            commit('SET_TOKEN', data.token)
            setToken(data.token)
          }

          resolve(response)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token)
        .then((response) => {
          // const { data } = response
          if (response.success) {
            const { username, avatar } = response.result
            commit('SET_NAME', username)
            commit('SET_AVATAR', avatar)
            commit('SET_USERINFO', response.result)
          }

          resolve(response)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      sessionStorage.clear()
      removeToken() // must remove  token  first
      resetRouter()
      commit('RESET_STATE')
      resolve()
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  },
  getProvienceList({ commit }) {
    return new Promise((resolve) => {
      getProvience().then((res) => {
        if (res.success) {
          commit('SET_PROVIENCE', res.result)
          resolve(res.result)
        }
      })
    })
  },
  getCityList({ commit }, provinceId = '') {
    return new Promise((resolve) => {
      if (provinceId) {
        getCity({ provinceId }).then((res) => {
          if (res.success) {
            commit('SET_CITY', res.result)
            resolve(res.result)
          }
        })
      } else {
        resolve([])
      }
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
